package com.duobeiyun.gmstest

import android.content.Context
import android.util.Log
import com.duobeiyun.generamessagesdk.ErrorInfo
import com.duobeiyun.generamessagesdk.PeerSubscriptionOption
import com.duobeiyun.generamessagesdk.ResultCallback
import com.duobeiyun.generamessagesdk.bean.LoginParams
import com.duobeiyun.generamessagesdk.channel.GmsChannel
import com.duobeiyun.generamessagesdk.channel.GmsChannelListener
import com.duobeiyun.generamessagesdk.channel.bean.ChannelAttributeOptions
import com.duobeiyun.generamessagesdk.channel.bean.GmsChannelAttribute
import com.duobeiyun.generamessagesdk.client.GmsClient
import com.duobeiyun.generamessagesdk.client.GmsClientListener
import com.duobeiyun.generamessagesdk.connect.Connect
import com.duobeiyun.generamessagesdk.connect.bean.GmsMessage
import com.duobeiyun.generamessagesdk.invite.GmsInvitationEventListener
import com.duobeiyun.generamessagesdk.invite.Invitation
import com.duobeiyun.generamessagesdk.invite.InvitationManager
import com.duobeiyun.generamessagesdk.utils.TokenUtils
import com.duobeiyun.gmstest.log.LogDebug
import java.util.*
import java.util.Set

object TestInstance {

    val errorUserId by lazy {
        var stringBuilder = StringBuilder()
        for (i in 1..65) {
            stringBuilder.append("1")
        }
        stringBuilder.toString()
    }

    //    var userId = errorUserId
    var notExistPerson: String? = "notExistPerson"
    var userId: String? = "gmsandroid111"
    var targetUserId: String? = "111"

//    var userId: String? = "111"
//    var targetUserId:String? =  "gms_android"


    val channelId: String? = "123456"

    val onLineSet: Set<String> = setOf("111", "222", "333") as java.util.Set<String>

    var createInstance: GmsClient? = null
    var otherInstance: GmsClient? = null
    var createChannel999: GmsChannel? = null

/*appId 3d0b836bf04f4ad992526f5d4e9a7183
appKey b1463602d5c942c2a683721a300e7342*/

    //从官网获取，或者直接找相关人员
//    val TEST_APPID = "3d0b836bf04f4ad992526f5d4e9a7183";
//    val TEST_APPKEY = "b1463602d5c942c2a683721a300e7342";

    //dev
//    val TEST_APPID = "1824a0bff47e4f47bdce956c5e9025ad";
//    val TEST_APPKEY = "24f5595baa8645fd947051e75ffcdcc4";


    val TEST_APPID by lazy {
        return@lazy if (props.getProperty("isDebug").toBoolean()) {
            "1824a0bff47e4f47bdce956c5e9025ad"
        } else {
            "3d0b836bf04f4ad992526f5d4e9a7183"
        }
    }

    val TEST_APPKEY by lazy {
        return@lazy if (props.getProperty("isDebug").toBoolean()) {
            "24f5595baa8645fd947051e75ffcdcc4"
        } else {
            "b1463602d5c942c2a683721a300e7342"
        }
    }
    var props: Properties = Properties()

    //    var testManger: TestManager? = null
    var token: String? = null
    var timestamp: Long? = null
    var invitationManager: InvitationManager? = null
    var otherInvitationManager: InvitationManager? = null
    fun init(applicationContext: Context) {
        props.load(applicationContext.assets.open("params.properties"))
        //Android 自己测试呼叫邀请需要多台设备，demo：uid: gms_android 作为邀请方，uid：1111 作为被邀请方
        //用户可以随意设置
//        userId = "gms_android"// + Random.nextInt(1000).toString()
        /**此为demo 生成token，用户对接，需要从自己的服务器进行请求，不要将appkey放在客户端 不安全*/
        timestamp = 0
        Log.d(TAG, "init: TEST_APPID:$TEST_APPID TEST_APPKEY:$TEST_APPKEY")
        token = TokenUtils.createToke(TEST_APPID, userId, timestamp!!, TEST_APPKEY);
        createInstance = createClientInstance(applicationContext)
        invitationManager = createInstance?.getGmsCallManager()
        val testInviterIdDefault = "gms_android"

    }

    fun initOtherGmsClient(applicationContext: Context) {
        otherInstance = createClientInstance(applicationContext)
        otherInvitationManager = otherInstance?.getGmsCallManager()
    }

    private const val TAG = "TestInstance"
      var connectStateCode: Int = 0
      var connectStateReason: Int = 0
    private fun createClientInstance(applicationContext: Context): GmsClient {


        val createInstance = GmsClient.createInstance(
                applicationContext,
                TEST_APPID,
                object : GmsClientListener {
                    override fun onConnectionStateChanged(code: Int, reason: Int) {
                        // 连接状态发生改变
                        LogDebug.logD("GmsClientListener.onConnectionStateChanged $code   $reason")
                        connectStateCode = code
                        connectStateReason = reason
                        if (connectStateCode == Connect.CONNECTION_STATE_RECONNECTING){
                            LogDebug.logD("请手动连接网络,触发token过期")
                        }
                    }

                    override fun onMessageReceived(message: GmsMessage?, userId: String) {
                        LogDebug.logD("GmsClientListener.onMessageReceived $message   $userId")
                    }

                    override fun onPeersOnlineStatusChanged(map: Map<String, Int>) {
//                    PeerOnlineState int 对应值
                        LogDebug.logD("GmsClientListener.onPeersOnlineStatusChanged $map")
                    }

                    override fun onTokenExpired() {
                        LogDebug.logD("onTokenExpired")
                        /**此为demo 生成token，用户对接，需要从自己的服务器进行请求，不要将appkey放在客户端 不安全*/
                        timestamp = System.currentTimeMillis();
                        token = TokenUtils.createToke(TEST_APPID, userId, timestamp!!, TEST_APPKEY);
                        createInstance?.renewToken(LoginParams(token!!, userId!!, timestamp!!),
                                object : ResultCallback<Void> {
                                    override fun onSuccess(responseInfo: Void?) {
                                        LogDebug.logD("renewToken Success")

                                    }

                                    override fun onFailure(errorInfo: ErrorInfo) {
                                        LogDebug.logE("renewToken Failure")
                                    }

                                })
                    }
                })
        return createInstance
    }

    var resultCallback: ResultCallback<Void>? = null
    fun subscribePeersOnlineStatus(toSet: Set<String>, resultCallback: ResultCallback<Void>) {
        this.resultCallback = resultCallback
        createInstance?.subscribePeersOnlineStatus(toSet, resultCallback)
    }

    fun unsubscribePeersOnlineStatus(toSet: Set<String>) {
        createInstance?.subscribePeersOnlineStatus(toSet, resultCallback!!)
    }

    fun sendMessage(createMessage: GmsMessage?, resultCallback: ResultCallback<Void>) {
        createInstance?.sendMessageToPeer(createMessage!!, resultCallback)
    }

    fun createChannel(channelId: String, gmsChannelListener: GmsChannelListener, resultCallback: ResultCallback<Void>) {
        var chanel: GmsChannel? =
                createInstance?.createChannel(channelId, gmsChannelListener)

        chanel?.join(resultCallback)
    }

    fun setChannelAttributes(channelId: String,
                             list: List<GmsChannelAttribute>,
                             options: ChannelAttributeOptions,
                             resultCallback: ResultCallback<Void>) {
        createInstance?.setChannelAttributes(channelId, list, options, resultCallback)
    }

    fun acceptTest(param: GmsInvitationEventListener, resultCallback: ResultCallback<Invitation>) {

        var invitation = invitationManager?.create(/*userId!!*/"tdvbstvnsd")

        invitationManager?.setEventListener(param)

        invitationManager?.send(invitation!!, resultCallback)
    }



    fun login(loginParams: LoginParams, resultCallback: ResultCallback<Void>) {
        createInstance?.login(loginParams, resultCallback)
    }



    fun logout(resultCallback: ResultCallback<Void>) {
        createInstance?.logout(resultCallback)
    }

}


